package com.css.fxfzypg.modules.baseData.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.common.utils.CheckObjFields;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.baseData.dto.OthProjectDto;
import com.css.fxfzypg.modules.baseData.dto.SciExpProjectDto;
import com.css.fxfzypg.modules.baseData.entity.KeyProjectEntity;
import com.css.fxfzypg.modules.baseData.repository.KeyProjectRepository;
import com.css.fxfzypg.modules.baseData.repository.OthProjectRepository;
import com.css.fxfzypg.modules.baseData.service.OthProjectService;
import com.css.fxfzypg.modules.baseData.vo.OthProjectVo;
import com.css.fxfzypg.util.EasyPoiExcelUtil;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.util.UUIDGenerator;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author
 * @date 2022/10/6 11:07
 * @description
 **/
@Slf4j
@Service
public class OthProjectServiceImpl implements OthProjectService {
    @Autowired
    private KeyProjectRepository keyProjectRepository;

    @Autowired
    private OthProjectRepository othProjectRepository;

    @Autowired
    private SysAreaService sysAreaService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public String importOthProject(MultipartFile file, ImportParams params, String dkpKeyType) {
        Map<String,String> areaIdCodeMap = (Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"areaIdCodeMap"));
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            ExcelImportResult<OthProjectVo> result = ExcelImportUtil.importExcelMore(file.getInputStream(), OthProjectVo.class, params);

            List<OthProjectVo> list = result.getList();
            if (PlatformObjectUtils.isNotEmpty(list)) {
                for (OthProjectVo item : list) {

                    KeyProjectEntity KeyProject = new KeyProjectEntity();
                    BeanUtils.copyProperties(item, KeyProject);
                    String divisionIds = null;

                    //判断省市县的名称是否符合规范
                    divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(item.getDkpProvince(), "utf-8"),
                            URLEncoder.encode(item.getDkpCity(), "utf-8"),
                            URLEncoder.encode(item.getDkpPrefecture(), "utf-8"));

                    if(StringUtils.isBlank(divisionIds) || divisionIds.split("_").length<3){
                        return "导入失败，请检查"+item.getDkpProvince()+","+item.getDkpCity()+","+item.getDkpPrefecture()+"数据正确性";
                    }
                    String[] split = divisionIds.split("_");
                    KeyProject.setDkpProvinceId(split[0]);
                    KeyProject.setDkpCityId(split[1]);
                    KeyProject.setDkpPrefectureId(split[2]);
                    KeyProject.setDkpIsDelete(YNEnum.N.toString());
                    KeyProject.setDkpCreateUser(PlatformSessionContext.getUserID());
                    KeyProject.setDkpCreateTime(new Date());
                    KeyProject.setDkpId(UUIDGenerator.getUUID());
                    KeyProject.setDkpKeyType(dkpKeyType);
                    KeyProject.setProvinceCode(areaIdCodeMap.get(split[0]));
                    KeyProject.setCityCode(areaIdCodeMap.get(split[1]));
                    KeyProject.setPrefectureCode(areaIdCodeMap.get(split[2]));
                    keyProjectRepository.saveKeyProject(KeyProject);

                }
            }
            returnMsg.append("成功导入" + (result.getList().size()) + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<OthProjectVo> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    OthProjectVo peoVO = iterator.next();
                    KeyProjectEntity KeyProject = new KeyProjectEntity();
                    BeanUtils.copyProperties(peoVO, KeyProject);
                    if (CheckObjFields.isAllFieldNull(KeyProject)){
                        continue;
                    }
                    returnMsg.append("第" + peoVO.getRowNum() + "行 " + peoVO.getErrorMsg() + "<br/>");
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }

    @Override
    public void exportExcel(List<String> idList, HttpServletResponse response) {
        List<OthProjectDto> list=othProjectRepository.findInIdList(idList);
        try {
            List<OthProjectDto> dtoList = new ArrayList<>();
            for (String id : idList) {
                dtoList.addAll(list.stream().filter(l -> l.getDkpId().equals(id)).collect(Collectors.toList()));
            }
            EasyPoiExcelUtil.exportExcel(dtoList, "其他信息统计", "其他信息", OthProjectDto.class, "其他信息", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("导出成功");
    }

    @Override
    public void update(KeyProjectEntity keyProjectEntity) {
        othProjectRepository.update(keyProjectEntity);
    }
}
